<template>
  <div class="app-container">
    <!-- 搜索表单部分保持不变 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- 原有搜索条件保持不变 -->
      <el-form-item label="区域名称" prop="areaName">
        <el-input
          v-model="queryParams.areaName"
          placeholder="请输入区域名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 风险等级下拉选择 -->
      <el-form-item label="风险等级" prop="riskLevel">
        <el-select
          v-model="queryParams.riskLevel"
          placeholder="请选择风险等级"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="item in riskLevelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 负责人下拉选择 -->
      <el-form-item label="负责人" prop="responsiblePerson">
        <el-select
          v-model="queryParams.responsiblePerson"
          placeholder="请选择负责人"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="item in personOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 责任部门 -->
      <el-form-item label="责任部门" prop="deptId">
        <treeselect
          v-model="queryParams.deptId"
          :options="enabledDeptOptions"
          :show-count="true"
          placeholder="请选择责任部门"
          clearable
          @change="handleQuery"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域保持不变 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:region:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:region:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:region:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:region:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格区域保持不变 -->
    <el-table
      v-loading="loading"
      :data="regionList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="区域名称" align="center" prop="areaName" />
      <el-table-column label="编码" align="center" prop="code" />
      <!-- 风险等级映射显示 -->
      <el-table-column label="风险等级" align="center">
        <template slot-scope="scope">
          {{ riskLevelMap[scope.row.riskLevel] || '未知风险' }}
        </template>
      </el-table-column>
      <el-table-column label="负责人" align="center" prop="responsiblePerson" />
      <!-- 责任部门 -->
      <el-table-column label="责任部门" align="center">
        <template slot-scope="scope">
          {{ deptIdMap[scope.row.deptId] || '未知部门' }}
        </template>
      </el-table-column>
      <!-- 新增：上级城市显示列 -->
      <el-table-column label="上级城市" align="center">
        <template slot-scope="scope">
          {{ getCityName(scope.row.parentId) }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:region:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:region:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="Number(total)"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改区域对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="110px"
        class="two-column-form"
      >
        <el-row :gutter="20">
          <!-- 第一列 -->
          <el-col :xs="24" :sm="12">
            <!-- 修改：将原来的区域树选择改为城市下拉框 -->
            <el-form-item label="上级城市" prop="parentId">
              <el-select
                v-model="form.parentId"
                placeholder="请选择上级城市"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="city in cityOptions"
                  :key="city.value"
                  :label="city.label"
                  :value="city.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 风险等级下拉选择 -->
            <el-form-item label="固有风险等级" prop="riskLevel">
              <el-select
                v-model="form.riskLevel"
                placeholder="请选择风险等级"
                style="width: 100%"
              >
                <el-option
                  v-for="item in riskLevelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- 负责人下拉选择 -->
            <el-form-item label="责任人" prop="responsiblePerson">
              <el-select
                v-model="form.responsiblePerson"
                placeholder="请选择责任人"
                style="width: 100%"
              >
                <el-option
                  v-for="item in personOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 第二列 -->
          <el-col :xs="24" :sm="12">
            <el-form-item label="区域编码" prop="code">
              <el-input
                v-model="form.code"
                placeholder="请输入区域编码"
              ></el-input>
            </el-form-item>
            <el-form-item label="区域名称" prop="areaName">
              <el-input
                v-model="form.areaName"
                placeholder="请输入区域名称"
              ></el-input>
            </el-form-item>
            <!-- 归属部门 -->
            <el-form-item label="归属部门" prop="deptId">
              <treeselect 
                v-model="form.deptId" 
                :options="enabledDeptOptions" 
                :show-count="true" 
                placeholder="请选择归属部门" 
              />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 单列区域 -->
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="请输入内容"
            :rows="4"
          ></el-input>
        </el-form-item>
        <el-form-item label="其他区域属性" prop="otherProperties">
          <el-input
            type="textarea"
            v-model="form.otherProperties"
            placeholder="请输入内容"
            :rows="4"
          ></el-input>
        </el-form-item>
        <el-form-item label="地图坐标" prop="coordinates">
          <el-input style="width: 450px;"
            v-model="form.coordinates"
            placeholder="请输入地图坐标"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRegion,
  getRegion,
  delRegion,
  addRegion,
  updateRegion,
  deptTreeSelect,
} from "@/api/system/region";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Region",
  components: { Treeselect },
  data() {
    return {
      // 风险等级映射关系
      riskLevelMap: {
        "1": "低风险",
        "2": "一般风险", 
        "3": "较大风险"
      },
      // 风险等级下拉选项
      riskLevelOptions: [
        { label: "低风险", value: "1" },
        { label: "一般风险", value: "2" },
        { label: "较大风险", value: "3" }
      ],
      // 负责人下拉选项
      personOptions: [
        { label: "张三", value: "张三" },
        { label: "李四", value: "李四" },
        { label: "王五", value: "王五" }
      ],
      // 新增：城市下拉选项 - 三个城市对应三个数字
      cityOptions: [
        { label: "北京", value: 1 },
        { label: "上海", value: 2 },
        { label: "广州", value: 3 }
      ],
      // 城市映射关系（用于表格显示）
      cityMap: {
        1: "北京",
        2: "上海", 
        3: "广州"
      },
      // 部门映射
      deptIdMap: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 部门树相关
      deptOptions: undefined,
      enabledDeptOptions: undefined,
      // 移除了原来的区域树选项
      // regionTreeOptions: undefined,
      // 区域表格数据
      regionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaName: null,
        code: null,
        riskLevel: null,
        responsiblePerson: null,
        deptId: undefined,
        parentId: null, // 新增：上级城市查询条件
        remark: null,
        otherProperties: null,
        coordinates: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        areaName: [
          { required: true, message: "请输入区域名称", trigger: "blur" },
        ],
        code: [{ required: true, message: "请输入编码", trigger: "blur" }],
        // 修改：将原来的parentId必填规则改为可选，因为现在是用城市下拉框
        // parentId: [
        //   { required: true, message: "请选择上级城市", trigger: "change" },
        // ],
        riskLevel: [
          { required: true, message: "请选择风险等级", trigger: "change" },
        ],
        responsiblePerson: [
          { required: true, message: "请选择责任人", trigger: "change" },
        ],
        deptId: [
          { required: true, message: "请选择责任部门", trigger: "change" },
        ],
      },
    };
  },
  
  created() {
    this.getList();
    this.getDeptTree(); // 加载部门树
    // 移除了原来的区域树加载
    // this.getRegionTree();
  },
  methods: {
    /** 查询区域列表 */
    getList() {
      this.loading = true;
      listRegion(this.queryParams)
        .then((response) => {
          this.regionList = response.rows || [];
          this.total = response.total || 0;
          this.loading = false;
        })
        .catch((error) => {
          console.error("获取区域列表失败:", error);
          this.loading = false;
          this.regionList = [];
          this.total = 0;
        });
    },

    /** 部门树相关 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
        // 过滤禁用部门
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
        // 动态生成deptIdMap
        this.buildDeptIdMap(response.data);
      });
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter((dept) => {
        if (dept.disabled) return false;
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children);
        }
        return true;
      });
    },
    // 构建部门ID→名称映射
    buildDeptIdMap(deptList) {
      deptList.forEach(dept => {
        this.deptIdMap[dept.id] = dept.label;
        if (dept.children && dept.children.length) {
          this.buildDeptIdMap(dept.children);
        }
      });
    },

    /** 新增：根据数字获取城市名称（用于表格显示） */
    getCityName(cityValue) {
      return this.cityMap[cityValue] || '未选择';
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        areaName: null,
        code: null,
        riskLevel: null,
        responsiblePerson: null,
        deptId: null,
        parentId: null, // 上级城市ID（数字）
        remark: null,
        otherProperties: null,
        coordinates: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.queryParams.parentId = null; // 重置上级城市查询条件
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加区域信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row ? row.id : this.ids[0];
      getRegion(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改区域";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 在这里，form.parentId 已经是数字（1,2,3），直接传给后端
          if (this.form.id != null) {
            updateRegion(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRegion(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row ? [row.id] : this.ids;
      this.$modal
        .confirm(`是否确认删除区域编号为"${ids.join(",")}"的数据项？`)
        .then(() => {
          return delRegion(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/region/export",
        {
          ...this.queryParams,
        },
        `region_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>